home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / python2.4 / urllib.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2007-04-29  |  43.8 KB  |  1,663 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.4)
  3.  
  4. '''Open an arbitrary URL.
  5.  
  6. See the following document for more info on URLs:
  7. "Names and Addresses, URIs, URLs, URNs, URCs", at
  8. http://www.w3.org/pub/WWW/Addressing/Overview.html
  9.  
  10. See also the HTTP spec (from which the error codes are derived):
  11. "HTTP - Hypertext Transfer Protocol", at
  12. http://www.w3.org/pub/WWW/Protocols/
  13.  
  14. Related standards and specs:
  15. - RFC1808: the "relative URL" spec. (authoritative status)
  16. - RFC1738 - the "URL standard". (authoritative status)
  17. - RFC1630 - the "URI spec". (informational status)
  18.  
  19. The object returned by URLopener().open(file) will differ per
  20. protocol.  All you know is that is has methods read(), readline(),
  21. readlines(), fileno(), close() and info().  The read*(), fileno()
  22. and close() methods work like those of open files.
  23. The info() method returns a mimetools.Message object which can be
  24. used to query various info about the object, if available.
  25. (mimetools.Message objects are queried with the getheader() method.)
  26. '''
  27. import string
  28. import socket
  29. import os
  30. import time
  31. import sys
  32. from urlparse import urljoin as basejoin
  33. __all__ = [
  34.     'urlopen',
  35.     'URLopener',
  36.     'FancyURLopener',
  37.     'urlretrieve',
  38.     'urlcleanup',
  39.     'quote',
  40.     'quote_plus',
  41.     'unquote',
  42.     'unquote_plus',
  43.     'urlencode',
  44.     'url2pathname',
  45.     'pathname2url',
  46.     'splittag',
  47.     'localhost',
  48.     'thishost',
  49.     'ftperrors',
  50.     'basejoin',
  51.     'unwrap',
  52.     'splittype',
  53.     'splithost',
  54.     'splituser',
  55.     'splitpasswd',
  56.     'splitport',
  57.     'splitnport',
  58.     'splitquery',
  59.     'splitattr',
  60.     'splitvalue',
  61.     'splitgophertype',
  62.     'getproxies']
  63. __version__ = '1.16'
  64. MAXFTPCACHE = 10
  65. if os.name == 'mac':
  66.     from macurl2path import url2pathname, pathname2url
  67. elif os.name == 'nt':
  68.     from nturl2path import url2pathname, pathname2url
  69. elif os.name == 'riscos':
  70.     from rourl2path import url2pathname, pathname2url
  71. else:
  72.     
  73.     def url2pathname(pathname):
  74.         """OS-specific conversion from a relative URL of the 'file' scheme
  75.         to a file system path; not recommended for general use."""
  76.         return unquote(pathname)
  77.  
  78.     
  79.     def pathname2url(pathname):
  80.         """OS-specific conversion from a file system path to a relative URL
  81.         of the 'file' scheme; not recommended for general use."""
  82.         return quote(pathname)
  83.  
  84. _urlopener = None
  85.  
  86. def urlopen(url, data = None, proxies = None):
  87.     '''urlopen(url [, data]) -> open file-like object'''
  88.     global _urlopener
  89.     if proxies is not None:
  90.         opener = FancyURLopener(proxies = proxies)
  91.     elif not _urlopener:
  92.         opener = FancyURLopener()
  93.         _urlopener = opener
  94.     else:
  95.         opener = _urlopener
  96.     if data is None:
  97.         return opener.open(url)
  98.     else:
  99.         return opener.open(url, data)
  100.  
  101.  
  102. def urlretrieve(url, filename = None, reporthook = None, data = None):
  103.     global _urlopener
  104.     if not _urlopener:
  105.         _urlopener = FancyURLopener()
  106.     
  107.     return _urlopener.retrieve(url, filename, reporthook, data)
  108.  
  109.  
  110. def urlcleanup():
  111.     if _urlopener:
  112.         _urlopener.cleanup()
  113.     
  114.  
  115.  
  116. class ContentTooShortError(IOError):
  117.     
  118.     def __init__(self, message, content):
  119.         IOError.__init__(self, message)
  120.         self.content = content
  121.  
  122.  
  123. ftpcache = { }
  124.  
  125. class URLopener:
  126.     """Class to open URLs.
  127.     This is a class rather than just a subroutine because we may need
  128.     more than one set of global protocol-specific options.
  129.     Note -- this is a base class for those who don't want the
  130.     automatic handling of errors type 302 (relocated) and 401
  131.     (authorization needed)."""
  132.     __tempfiles = None
  133.     version = 'Python-urllib/%s' % __version__
  134.     
  135.     def __init__(self, proxies = None, **x509):
  136.         if proxies is None:
  137.             proxies = getproxies()
  138.         
  139.         if not hasattr(proxies, 'has_key'):
  140.             raise AssertionError, 'proxies must be a mapping'
  141.         self.proxies = proxies
  142.         self.key_file = x509.get('key_file')
  143.         self.cert_file = x509.get('cert_file')
  144.         self.addheaders = [
  145.             ('User-agent', self.version)]
  146.         self._URLopener__tempfiles = []
  147.         self._URLopener__unlink = os.unlink
  148.         self.tempcache = None
  149.         self.ftpcache = ftpcache
  150.  
  151.     
  152.     def __del__(self):
  153.         self.close()
  154.  
  155.     
  156.     def close(self):
  157.         self.cleanup()
  158.  
  159.     
  160.     def cleanup(self):
  161.         if self._URLopener__tempfiles:
  162.             for file in self._URLopener__tempfiles:
  163.                 
  164.                 try:
  165.                     self._URLopener__unlink(file)
  166.                 continue
  167.                 except OSError:
  168.                     continue
  169.                 
  170.  
  171.             
  172.             del self._URLopener__tempfiles[:]
  173.         
  174.         if self.tempcache:
  175.             self.tempcache.clear()
  176.         
  177.  
  178.     
  179.     def addheader(self, *args):
  180.         """Add a header to be used by the HTTP interface only
  181.         e.g. u.addheader('Accept', 'sound/basic')"""
  182.         self.addheaders.append(args)
  183.  
  184.     
  185.     def open(self, fullurl, data = None):
  186.         """Use URLopener().open(file) instead of open(file, 'r')."""
  187.         fullurl = unwrap(toBytes(fullurl))
  188.         if self.tempcache and fullurl in self.tempcache:
  189.             (filename, headers) = self.tempcache[fullurl]
  190.             fp = open(filename, 'rb')
  191.             return addinfourl(fp, headers, fullurl)
  192.         
  193.         (urltype, url) = splittype(fullurl)
  194.         if not urltype:
  195.             urltype = 'file'
  196.         
  197.         if urltype in self.proxies:
  198.             proxy = self.proxies[urltype]
  199.             (urltype, proxyhost) = splittype(proxy)
  200.             (host, selector) = splithost(proxyhost)
  201.             url = (host, fullurl)
  202.         else:
  203.             proxy = None
  204.         name = 'open_' + urltype
  205.         self.type = urltype
  206.         name = name.replace('-', '_')
  207.         if not hasattr(self, name):
  208.             if proxy:
  209.                 return self.open_unknown_proxy(proxy, fullurl, data)
  210.             else:
  211.                 return self.open_unknown(fullurl, data)
  212.         
  213.         
  214.         try:
  215.             if data is None:
  216.                 return getattr(self, name)(url)
  217.             else:
  218.                 return getattr(self, name)(url, data)
  219.         except socket.error:
  220.             msg = None
  221.             raise IOError, ('socket error', msg), sys.exc_info()[2]
  222.  
  223.  
  224.     
  225.     def open_unknown(self, fullurl, data = None):
  226.         '''Overridable interface to open unknown URL type.'''
  227.         (type, url) = splittype(fullurl)
  228.         raise IOError, ('url error', 'unknown url type', type)
  229.  
  230.     
  231.     def open_unknown_proxy(self, proxy, fullurl, data = None):
  232.         '''Overridable interface to open unknown URL type.'''
  233.         (type, url) = splittype(fullurl)
  234.         raise IOError, ('url error', 'invalid proxy for %s' % type, proxy)
  235.  
  236.     
  237.     def retrieve(self, url, filename = None, reporthook = None, data = None):
  238.         '''retrieve(url) returns (filename, headers) for a local object
  239.         or (tempfilename, headers) for a remote object.'''
  240.         url = unwrap(toBytes(url))
  241.         if self.tempcache and url in self.tempcache:
  242.             return self.tempcache[url]
  243.         
  244.         (type, url1) = splittype(url)
  245.         if filename is None:
  246.             if not type or type == 'file':
  247.                 
  248.                 try:
  249.                     fp = self.open_local_file(url1)
  250.                     hdrs = fp.info()
  251.                     del fp
  252.                     return (url2pathname(splithost(url1)[1]), hdrs)
  253.                 except IOError:
  254.                     msg = None
  255.                 except:
  256.                     None<EXCEPTION MATCH>IOError
  257.                 
  258.  
  259.         None<EXCEPTION MATCH>IOError
  260.         fp = self.open(url, data)
  261.         headers = fp.info()
  262.         if filename:
  263.             tfp = open(filename, 'wb')
  264.         else:
  265.             import tempfile
  266.             (garbage, path) = splittype(url)
  267.             if not path:
  268.                 pass
  269.             (garbage, path) = splithost('')
  270.             if not path:
  271.                 pass
  272.             (path, garbage) = splitquery('')
  273.             if not path:
  274.                 pass
  275.             (path, garbage) = splitattr('')
  276.             suffix = os.path.splitext(path)[1]
  277.             (fd, filename) = tempfile.mkstemp(suffix)
  278.             self._URLopener__tempfiles.append(filename)
  279.             tfp = os.fdopen(fd, 'wb')
  280.         result = (filename, headers)
  281.         if self.tempcache is not None:
  282.             self.tempcache[url] = result
  283.         
  284.         bs = 1024 * 8
  285.         size = -1
  286.         read = 0
  287.         blocknum = 0
  288.         if reporthook:
  289.             if 'content-length' in headers:
  290.                 size = int(headers['Content-Length'])
  291.             
  292.             reporthook(blocknum, bs, size)
  293.         
  294.         while None:
  295.             block = fp.read(bs)
  296.             if block == '':
  297.                 break
  298.             
  299.             read += len(block)
  300.             blocknum += 1
  301.             if reporthook:
  302.                 reporthook(blocknum, bs, size)
  303.                 continue
  304.         fp.close()
  305.         tfp.close()
  306.         del fp
  307.         del tfp
  308.         if size >= 0 and read < size:
  309.             raise ContentTooShortError('retrieval incomplete: got only %i out of %i bytes' % (read, size), result)
  310.         
  311.         return result
  312.  
  313.     
  314.     def open_http(self, url, data = None):
  315.         '''Use HTTP protocol.'''
  316.         import httplib
  317.         user_passwd = None
  318.         if isinstance(url, str):
  319.             (host, selector) = splithost(url)
  320.             if host:
  321.                 (user_passwd, host) = splituser(host)
  322.                 host = unquote(host)
  323.             
  324.             realhost = host
  325.         else:
  326.             (host, selector) = url
  327.             (urltype, rest) = splittype(selector)
  328.             url = rest
  329.             user_passwd = None
  330.             if urltype.lower() != 'http':
  331.                 realhost = None
  332.             else:
  333.                 (realhost, rest) = splithost(rest)
  334.                 if realhost:
  335.                     (user_passwd, realhost) = splituser(realhost)
  336.                 
  337.                 if user_passwd:
  338.                     selector = '%s://%s%s' % (urltype, realhost, rest)
  339.                 
  340.                 if proxy_bypass(realhost):
  341.                     host = realhost
  342.                 
  343.         if not host:
  344.             raise IOError, ('http error', 'no host given')
  345.         
  346.         if user_passwd:
  347.             import base64
  348.             auth = base64.encodestring(user_passwd).strip()
  349.         else:
  350.             auth = None
  351.         h = httplib.HTTP(host)
  352.         if data is not None:
  353.             h.putrequest('POST', selector)
  354.             h.putheader('Content-type', 'application/x-www-form-urlencoded')
  355.             h.putheader('Content-length', '%d' % len(data))
  356.         else:
  357.             h.putrequest('GET', selector)
  358.         if auth:
  359.             h.putheader('Authorization', 'Basic %s' % auth)
  360.         
  361.         if realhost:
  362.             h.putheader('Host', realhost)
  363.         
  364.         for args in self.addheaders:
  365.             h.putheader(*args)
  366.         
  367.         h.endheaders()
  368.         if data is not None:
  369.             h.send(data)
  370.         
  371.         (errcode, errmsg, headers) = h.getreply()
  372.         fp = h.getfile()
  373.         if errcode == 200:
  374.             return addinfourl(fp, headers, 'http:' + url)
  375.         elif data is None:
  376.             return self.http_error(url, fp, errcode, errmsg, headers)
  377.         else:
  378.             return self.http_error(url, fp, errcode, errmsg, headers, data)
  379.  
  380.     
  381.     def http_error(self, url, fp, errcode, errmsg, headers, data = None):
  382.         '''Handle http errors.
  383.         Derived class can override this, or provide specific handlers
  384.         named http_error_DDD where DDD is the 3-digit error code.'''
  385.         name = 'http_error_%d' % errcode
  386.         if hasattr(self, name):
  387.             method = getattr(self, name)
  388.             if data is None:
  389.                 result = method(url, fp, errcode, errmsg, headers)
  390.             else:
  391.                 result = method(url, fp, errcode, errmsg, headers, data)
  392.             if result:
  393.                 return result
  394.             
  395.         
  396.         return self.http_error_default(url, fp, errcode, errmsg, headers)
  397.  
  398.     
  399.     def http_error_default(self, url, fp, errcode, errmsg, headers):
  400.         '''Default error handler: close the connection and raise IOError.'''
  401.         void = fp.read()
  402.         fp.close()
  403.         raise IOError, ('http error', errcode, errmsg, headers)
  404.  
  405.     if hasattr(socket, 'ssl'):
  406.         
  407.         def open_https(self, url, data = None):
  408.             '''Use HTTPS protocol.'''
  409.             import httplib
  410.             user_passwd = None
  411.             if isinstance(url, str):
  412.                 (host, selector) = splithost(url)
  413.                 if host:
  414.                     (user_passwd, host) = splituser(host)
  415.                     host = unquote(host)
  416.                 
  417.                 realhost = host
  418.             else:
  419.                 (host, selector) = url
  420.                 (urltype, rest) = splittype(selector)
  421.                 url = rest
  422.                 user_passwd = None
  423.                 if urltype.lower() != 'https':
  424.                     realhost = None
  425.                 else:
  426.                     (realhost, rest) = splithost(rest)
  427.                     if realhost:
  428.                         (user_passwd, realhost) = splituser(realhost)
  429.                     
  430.                     if user_passwd:
  431.                         selector = '%s://%s%s' % (urltype, realhost, rest)
  432.                     
  433.             if not host:
  434.                 raise IOError, ('https error', 'no host given')
  435.             
  436.             if user_passwd:
  437.                 import base64
  438.                 auth = base64.encodestring(user_passwd).strip()
  439.             else:
  440.                 auth = None
  441.             h = httplib.HTTPS(host, 0, key_file = self.key_file, cert_file = self.cert_file)
  442.             if data is not None:
  443.                 h.putrequest('POST', selector)
  444.                 h.putheader('Content-type', 'application/x-www-form-urlencoded')
  445.                 h.putheader('Content-length', '%d' % len(data))
  446.             else:
  447.                 h.putrequest('GET', selector)
  448.             if auth:
  449.                 h.putheader('Authorization', 'Basic %s' % auth)
  450.             
  451.             if realhost:
  452.                 h.putheader('Host', realhost)
  453.             
  454.             for args in self.addheaders:
  455.                 h.putheader(*args)
  456.             
  457.             h.endheaders()
  458.             if data is not None:
  459.                 h.send(data)
  460.             
  461.             (errcode, errmsg, headers) = h.getreply()
  462.             fp = h.getfile()
  463.             if errcode == 200:
  464.                 return addinfourl(fp, headers, 'https:' + url)
  465.             elif data is None:
  466.                 return self.http_error(url, fp, errcode, errmsg, headers)
  467.             else:
  468.                 return self.http_error(url, fp, errcode, errmsg, headers, data)
  469.  
  470.     
  471.     
  472.     def open_gopher(self, url):
  473.         '''Use Gopher protocol.'''
  474.         import gopherlib
  475.         (host, selector) = splithost(url)
  476.         if not host:
  477.             raise IOError, ('gopher error', 'no host given')
  478.         
  479.         host = unquote(host)
  480.         (type, selector) = splitgophertype(selector)
  481.         (selector, query) = splitquery(selector)
  482.         selector = unquote(selector)
  483.         if query:
  484.             query = unquote(query)
  485.             fp = gopherlib.send_query(selector, query, host)
  486.         else:
  487.             fp = gopherlib.send_selector(selector, host)
  488.         return addinfourl(fp, noheaders(), 'gopher:' + url)
  489.  
  490.     
  491.     def open_file(self, url):
  492.         '''Use local file or FTP depending on form of URL.'''
  493.         if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
  494.             return self.open_ftp(url)
  495.         else:
  496.             return self.open_local_file(url)
  497.  
  498.     
  499.     def open_local_file(self, url):
  500.         '''Use local file.'''
  501.         import mimetypes
  502.         import mimetools
  503.         import email.Utils as email
  504.         
  505.         try:
  506.             StringIO = StringIO
  507.             import cStringIO
  508.         except ImportError:
  509.             StringIO = StringIO
  510.             import StringIO
  511.  
  512.         (host, file) = splithost(url)
  513.         localname = url2pathname(file)
  514.         
  515.         try:
  516.             stats = os.stat(localname)
  517.         except OSError:
  518.             e = None
  519.             raise IOError(e.errno, e.strerror, e.filename)
  520.  
  521.         size = stats.st_size
  522.         modified = email.Utils.formatdate(stats.st_mtime, usegmt = True)
  523.         mtype = mimetypes.guess_type(url)[0]
  524.         if not mtype:
  525.             pass
  526.         headers = mimetools.Message(StringIO('Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % ('text/plain', size, modified)))
  527.         if not host:
  528.             urlfile = file
  529.             if file[:1] == '/':
  530.                 urlfile = 'file://' + file
  531.             
  532.             return addinfourl(open(localname, 'rb'), headers, urlfile)
  533.         
  534.         (host, port) = splitport(host)
  535.         if not port and socket.gethostbyname(host) in (localhost(), thishost()):
  536.             urlfile = file
  537.             if file[:1] == '/':
  538.                 urlfile = 'file://' + file
  539.             
  540.             return addinfourl(open(localname, 'rb'), headers, urlfile)
  541.         
  542.         raise IOError, ('local file error', 'not on local host')
  543.  
  544.     
  545.     def open_ftp(self, url):
  546.         '''Use FTP protocol.'''
  547.         import mimetypes
  548.         import mimetools
  549.         
  550.         try:
  551.             StringIO = StringIO
  552.             import cStringIO
  553.         except ImportError:
  554.             StringIO = StringIO
  555.             import StringIO
  556.  
  557.         (host, path) = splithost(url)
  558.         if not host:
  559.             raise IOError, ('ftp error', 'no host given')
  560.         
  561.         (host, port) = splitport(host)
  562.         (user, host) = splituser(host)
  563.         if user:
  564.             (user, passwd) = splitpasswd(user)
  565.         else:
  566.             passwd = None
  567.         host = unquote(host)
  568.         if not user:
  569.             pass
  570.         user = unquote('')
  571.         if not passwd:
  572.             pass
  573.         passwd = unquote('')
  574.         host = socket.gethostbyname(host)
  575.         if not port:
  576.             import ftplib
  577.             port = ftplib.FTP_PORT
  578.         else:
  579.             port = int(port)
  580.         (path, attrs) = splitattr(path)
  581.         path = unquote(path)
  582.         dirs = path.split('/')
  583.         dirs = dirs[:-1]
  584.         file = dirs[-1]
  585.         if dirs and not dirs[0]:
  586.             dirs = dirs[1:]
  587.         
  588.         if dirs and not dirs[0]:
  589.             dirs[0] = '/'
  590.         
  591.         key = (user, host, port, '/'.join(dirs))
  592.         if len(self.ftpcache) > MAXFTPCACHE:
  593.             for k in self.ftpcache.keys():
  594.                 if k != key:
  595.                     v = self.ftpcache[k]
  596.                     del self.ftpcache[k]
  597.                     v.close()
  598.                     continue
  599.             
  600.         
  601.         
  602.         try:
  603.             if key not in self.ftpcache:
  604.                 self.ftpcache[key] = ftpwrapper(user, passwd, host, port, dirs)
  605.             
  606.             if not file:
  607.                 type = 'D'
  608.             else:
  609.                 type = 'I'
  610.             for attr in attrs:
  611.                 (attr, value) = splitvalue(attr)
  612.                 if attr.lower() == 'type' and value in ('a', 'A', 'i', 'I', 'd', 'D'):
  613.                     type = value.upper()
  614.                     continue
  615.             
  616.             (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
  617.             mtype = mimetypes.guess_type('ftp:' + url)[0]
  618.             headers = ''
  619.             if mtype:
  620.                 headers += 'Content-Type: %s\n' % mtype
  621.             
  622.             if retrlen is not None and retrlen >= 0:
  623.                 headers += 'Content-Length: %d\n' % retrlen
  624.             
  625.             headers = mimetools.Message(StringIO(headers))
  626.             return addinfourl(fp, headers, 'ftp:' + url)
  627.         except ftperrors():
  628.             msg = None
  629.             raise IOError, ('ftp error', msg), sys.exc_info()[2]
  630.  
  631.  
  632.     
  633.     def open_data(self, url, data = None):
  634.         '''Use "data" URL.'''
  635.         import mimetools
  636.         
  637.         try:
  638.             StringIO = StringIO
  639.             import cStringIO
  640.         except ImportError:
  641.             StringIO = StringIO
  642.             import StringIO
  643.  
  644.         
  645.         try:
  646.             (type, data) = url.split(',', 1)
  647.         except ValueError:
  648.             raise IOError, ('data error', 'bad data URL')
  649.  
  650.         if not type:
  651.             type = 'text/plain;charset=US-ASCII'
  652.         
  653.         semi = type.rfind(';')
  654.         if semi >= 0 and '=' not in type[semi:]:
  655.             encoding = type[semi + 1:]
  656.             type = type[:semi]
  657.         else:
  658.             encoding = ''
  659.         msg = []
  660.         msg.append('Date: %s' % time.strftime('%a, %d %b %Y %T GMT', time.gmtime(time.time())))
  661.         msg.append('Content-type: %s' % type)
  662.         if encoding == 'base64':
  663.             import base64
  664.             data = base64.decodestring(data)
  665.         else:
  666.             data = unquote(data)
  667.         msg.append('Content-length: %d' % len(data))
  668.         msg.append('')
  669.         msg.append(data)
  670.         msg = '\n'.join(msg)
  671.         f = StringIO(msg)
  672.         headers = mimetools.Message(f, 0)
  673.         return addinfourl(f, headers, url)
  674.  
  675.  
  676.  
  677. class FancyURLopener(URLopener):
  678.     '''Derived class with handlers for errors we can handle (perhaps).'''
  679.     
  680.     def __init__(self, *args, **kwargs):
  681.         URLopener.__init__(self, *args, **kwargs)
  682.         self.auth_cache = { }
  683.         self.tries = 0
  684.         self.maxtries = 10
  685.  
  686.     
  687.     def http_error_default(self, url, fp, errcode, errmsg, headers):
  688.         """Default error handling -- don't raise an exception."""
  689.         return addinfourl(fp, headers, 'http:' + url)
  690.  
  691.     
  692.     def http_error_302(self, url, fp, errcode, errmsg, headers, data = None):
  693.         '''Error 302 -- relocated (temporarily).'''
  694.         self.tries += 1
  695.         result = self.redirect_internal(url, fp, errcode, errmsg, headers, data)
  696.         self.tries = 0
  697.         return result
  698.  
  699.     
  700.     def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
  701.         if 'location' in headers:
  702.             newurl = headers['location']
  703.         elif 'uri' in headers:
  704.             newurl = headers['uri']
  705.         else:
  706.             return None
  707.         void = fp.read()
  708.         fp.close()
  709.         newurl = basejoin(self.type + ':' + url, newurl)
  710.         return self.open(newurl)
  711.  
  712.     
  713.     def http_error_301(self, url, fp, errcode, errmsg, headers, data = None):
  714.         '''Error 301 -- also relocated (permanently).'''
  715.         return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  716.  
  717.     
  718.     def http_error_303(self, url, fp, errcode, errmsg, headers, data = None):
  719.         '''Error 303 -- also relocated (essentially identical to 302).'''
  720.         return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  721.  
  722.     
  723.     def http_error_307(self, url, fp, errcode, errmsg, headers, data = None):
  724.         '''Error 307 -- relocated, but turn POST into error.'''
  725.         if data is None:
  726.             return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  727.         else:
  728.             return self.http_error_default(url, fp, errcode, errmsg, headers)
  729.  
  730.     
  731.     def http_error_401(self, url, fp, errcode, errmsg, headers, data = None):
  732.         '''Error 401 -- authentication required.
  733.         See this URL for a description of the basic authentication scheme:
  734.         http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt'''
  735.         if 'www-authenticate' not in headers:
  736.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  737.         
  738.         stuff = headers['www-authenticate']
  739.         import re
  740.         match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
  741.         if not match:
  742.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  743.         
  744.         (scheme, realm) = match.groups()
  745.         if scheme.lower() != 'basic':
  746.             URLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
  747.         
  748.         name = 'retry_' + self.type + '_basic_auth'
  749.         if data is None:
  750.             return getattr(self, name)(url, realm)
  751.         else:
  752.             return getattr(self, name)(url, realm, data)
  753.  
  754.     
  755.     def retry_http_basic_auth(self, url, realm, data = None):
  756.         (host, selector) = splithost(url)
  757.         i = host.find('@') + 1
  758.         host = host[i:]
  759.         (user, passwd) = self.get_user_passwd(host, realm, i)
  760.         if not user or passwd:
  761.             return None
  762.         
  763.         host = quote(user, safe = '') + ':' + quote(passwd, safe = '') + '@' + host
  764.         newurl = 'http://' + host + selector
  765.         if data is None:
  766.             return self.open(newurl)
  767.         else:
  768.             return self.open(newurl, data)
  769.  
  770.     
  771.     def retry_https_basic_auth(self, url, realm, data = None):
  772.         (host, selector) = splithost(url)
  773.         i = host.find('@') + 1
  774.         host = host[i:]
  775.         (user, passwd) = self.get_user_passwd(host, realm, i)
  776.         if not user or passwd:
  777.             return None
  778.         
  779.         host = quote(user, safe = '') + ':' + quote(passwd, safe = '') + '@' + host
  780.         newurl = '//' + host + selector
  781.         return self.open_https(newurl, data)
  782.  
  783.     
  784.     def get_user_passwd(self, host, realm, clear_cache = 0):
  785.         key = realm + '@' + host.lower()
  786.         if key in self.auth_cache:
  787.             if clear_cache:
  788.                 del self.auth_cache[key]
  789.             else:
  790.                 return self.auth_cache[key]
  791.         
  792.         (user, passwd) = self.prompt_user_passwd(host, realm)
  793.         if user or passwd:
  794.             self.auth_cache[key] = (user, passwd)
  795.         
  796.         return (user, passwd)
  797.  
  798.     
  799.     def prompt_user_passwd(self, host, realm):
  800.         '''Override this in a GUI environment!'''
  801.         import getpass
  802.         
  803.         try:
  804.             user = raw_input('Enter username for %s at %s: ' % (realm, host))
  805.             passwd = getpass.getpass('Enter password for %s in %s at %s: ' % (user, realm, host))
  806.             return (user, passwd)
  807.         except KeyboardInterrupt:
  808.             print 
  809.             return (None, None)
  810.  
  811.  
  812.  
  813. _localhost = None
  814.  
  815. def localhost():
  816.     """Return the IP address of the magic hostname 'localhost'."""
  817.     global _localhost
  818.     if _localhost is None:
  819.         _localhost = socket.gethostbyname('localhost')
  820.     
  821.     return _localhost
  822.  
  823. _thishost = None
  824.  
  825. def thishost():
  826.     '''Return the IP address of the current host.'''
  827.     global _thishost
  828.     if _thishost is None:
  829.         _thishost = socket.gethostbyname(socket.gethostname())
  830.     
  831.     return _thishost
  832.  
  833. _ftperrors = None
  834.  
  835. def ftperrors():
  836.     '''Return the set of errors raised by the FTP class.'''
  837.     global _ftperrors
  838.     if _ftperrors is None:
  839.         import ftplib
  840.         _ftperrors = ftplib.all_errors
  841.     
  842.     return _ftperrors
  843.  
  844. _noheaders = None
  845.  
  846. def noheaders():
  847.     '''Return an empty mimetools.Message object.'''
  848.     global _noheaders
  849.     if _noheaders is None:
  850.         import mimetools
  851.         
  852.         try:
  853.             StringIO = StringIO
  854.             import cStringIO
  855.         except ImportError:
  856.             StringIO = StringIO
  857.             import StringIO
  858.  
  859.         _noheaders = mimetools.Message(StringIO(), 0)
  860.         _noheaders.fp.close()
  861.     
  862.     return _noheaders
  863.  
  864.  
  865. class ftpwrapper:
  866.     '''Class used by open_ftp() for cache of open FTP connections.'''
  867.     
  868.     def __init__(self, user, passwd, host, port, dirs):
  869.         self.user = user
  870.         self.passwd = passwd
  871.         self.host = host
  872.         self.port = port
  873.         self.dirs = dirs
  874.         self.init()
  875.  
  876.     
  877.     def init(self):
  878.         import ftplib
  879.         self.busy = 0
  880.         self.ftp = ftplib.FTP()
  881.         self.ftp.connect(self.host, self.port)
  882.         self.ftp.login(self.user, self.passwd)
  883.         for dir in self.dirs:
  884.             self.ftp.cwd(dir)
  885.         
  886.  
  887.     
  888.     def retrfile(self, file, type):
  889.         import ftplib
  890.         self.endtransfer()
  891.         if type in ('d', 'D'):
  892.             cmd = 'TYPE A'
  893.             isdir = 1
  894.         else:
  895.             cmd = 'TYPE ' + type
  896.             isdir = 0
  897.         
  898.         try:
  899.             self.ftp.voidcmd(cmd)
  900.         except ftplib.all_errors:
  901.             self.init()
  902.             self.ftp.voidcmd(cmd)
  903.  
  904.         conn = None
  905.         if file and not isdir:
  906.             
  907.             try:
  908.                 cmd = 'RETR ' + file
  909.                 conn = self.ftp.ntransfercmd(cmd)
  910.             except ftplib.error_perm:
  911.                 reason = None
  912.                 if str(reason)[:3] != '550':
  913.                     raise IOError, ('ftp error', reason), sys.exc_info()[2]
  914.                 
  915.             except:
  916.                 str(reason)[:3] != '550'
  917.             
  918.  
  919.         None<EXCEPTION MATCH>ftplib.error_perm
  920.         if not conn:
  921.             self.ftp.voidcmd('TYPE A')
  922.             if file:
  923.                 cmd = 'LIST ' + file
  924.             else:
  925.                 cmd = 'LIST'
  926.             conn = self.ftp.ntransfercmd(cmd)
  927.         
  928.         self.busy = 1
  929.         return (addclosehook(conn[0].makefile('rb'), self.endtransfer), conn[1])
  930.  
  931.     
  932.     def endtransfer(self):
  933.         if not self.busy:
  934.             return None
  935.         
  936.         self.busy = 0
  937.         
  938.         try:
  939.             self.ftp.voidresp()
  940.         except ftperrors():
  941.             pass
  942.  
  943.  
  944.     
  945.     def close(self):
  946.         self.endtransfer()
  947.         
  948.         try:
  949.             self.ftp.close()
  950.         except ftperrors():
  951.             pass
  952.  
  953.  
  954.  
  955.  
  956. class addbase:
  957.     '''Base class for addinfo and addclosehook.'''
  958.     
  959.     def __init__(self, fp):
  960.         self.fp = fp
  961.         self.read = self.fp.read
  962.         self.readline = self.fp.readline
  963.         if hasattr(self.fp, 'readlines'):
  964.             self.readlines = self.fp.readlines
  965.         
  966.         if hasattr(self.fp, 'fileno'):
  967.             self.fileno = self.fp.fileno
  968.         else:
  969.             
  970.             self.fileno = lambda : pass
  971.         if hasattr(self.fp, '__iter__'):
  972.             self.__iter__ = self.fp.__iter__
  973.             if hasattr(self.fp, 'next'):
  974.                 self.next = self.fp.next
  975.             
  976.         
  977.  
  978.     
  979.     def __repr__(self):
  980.         return '<%s at %r whose fp = %r>' % (self.__class__.__name__, id(self), self.fp)
  981.  
  982.     
  983.     def close(self):
  984.         self.read = None
  985.         self.readline = None
  986.         self.readlines = None
  987.         self.fileno = None
  988.         if self.fp:
  989.             self.fp.close()
  990.         
  991.         self.fp = None
  992.  
  993.  
  994.  
  995. class addclosehook(addbase):
  996.     '''Class to add a close hook to an open file.'''
  997.     
  998.     def __init__(self, fp, closehook, *hookargs):
  999.         addbase.__init__(self, fp)
  1000.         self.closehook = closehook
  1001.         self.hookargs = hookargs
  1002.  
  1003.     
  1004.     def close(self):
  1005.         addbase.close(self)
  1006.         if self.closehook:
  1007.             self.closehook(*self.hookargs)
  1008.             self.closehook = None
  1009.             self.hookargs = None
  1010.         
  1011.  
  1012.  
  1013.  
  1014. class addinfo(addbase):
  1015.     '''class to add an info() method to an open file.'''
  1016.     
  1017.     def __init__(self, fp, headers):
  1018.         addbase.__init__(self, fp)
  1019.         self.headers = headers
  1020.  
  1021.     
  1022.     def info(self):
  1023.         return self.headers
  1024.  
  1025.  
  1026.  
  1027. class addinfourl(addbase):
  1028.     '''class to add info() and geturl() methods to an open file.'''
  1029.     
  1030.     def __init__(self, fp, headers, url):
  1031.         addbase.__init__(self, fp)
  1032.         self.headers = headers
  1033.         self.url = url
  1034.  
  1035.     
  1036.     def info(self):
  1037.         return self.headers
  1038.  
  1039.     
  1040.     def geturl(self):
  1041.         return self.url
  1042.  
  1043.  
  1044.  
  1045. try:
  1046.     unicode
  1047. except NameError:
  1048.     
  1049.     def _is_unicode(x):
  1050.         return 0
  1051.  
  1052.  
  1053.  
  1054. def _is_unicode(x):
  1055.     return isinstance(x, unicode)
  1056.  
  1057.  
  1058. def toBytes(url):
  1059.     '''toBytes(u"URL") --> \'URL\'.'''
  1060.     if _is_unicode(url):
  1061.         
  1062.         try:
  1063.             url = url.encode('ASCII')
  1064.         except UnicodeError:
  1065.             raise UnicodeError('URL ' + repr(url) + ' contains non-ASCII characters')
  1066.         except:
  1067.             None<EXCEPTION MATCH>UnicodeError
  1068.         
  1069.  
  1070.     None<EXCEPTION MATCH>UnicodeError
  1071.     return url
  1072.  
  1073.  
  1074. def unwrap(url):
  1075.     """unwrap('<URL:type://host/path>') --> 'type://host/path'."""
  1076.     url = url.strip()
  1077.     if url[:1] == '<' and url[-1:] == '>':
  1078.         url = url[1:-1].strip()
  1079.     
  1080.     if url[:4] == 'URL:':
  1081.         url = url[4:].strip()
  1082.     
  1083.     return url
  1084.  
  1085. _typeprog = None
  1086.  
  1087. def splittype(url):
  1088.     """splittype('type:opaquestring') --> 'type', 'opaquestring'."""
  1089.     global _typeprog
  1090.     if _typeprog is None:
  1091.         import re
  1092.         _typeprog = re.compile('^([^/:]+):')
  1093.     
  1094.     match = _typeprog.match(url)
  1095.     if match:
  1096.         scheme = match.group(1)
  1097.         return (scheme.lower(), url[len(scheme) + 1:])
  1098.     
  1099.     return (None, url)
  1100.  
  1101. _hostprog = None
  1102.  
  1103. def splithost(url):
  1104.     """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
  1105.     global _hostprog
  1106.     if _hostprog is None:
  1107.         import re
  1108.         _hostprog = re.compile('^//([^/]*)(.*)$')
  1109.     
  1110.     match = _hostprog.match(url)
  1111.     if match:
  1112.         return match.group(1, 2)
  1113.     
  1114.     return (None, url)
  1115.  
  1116. _userprog = None
  1117.  
  1118. def splituser(host):
  1119.     """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
  1120.     global _userprog
  1121.     if _userprog is None:
  1122.         import re
  1123.         _userprog = re.compile('^(.*)@(.*)$')
  1124.     
  1125.     match = _userprog.match(host)
  1126.     if match:
  1127.         return map(unquote, match.group(1, 2))
  1128.     
  1129.     return (None, host)
  1130.  
  1131. _passwdprog = None
  1132.  
  1133. def splitpasswd(user):
  1134.     """splitpasswd('user:passwd') -> 'user', 'passwd'."""
  1135.     global _passwdprog
  1136.     if _passwdprog is None:
  1137.         import re
  1138.         _passwdprog = re.compile('^([^:]*):(.*)$')
  1139.     
  1140.     match = _passwdprog.match(user)
  1141.     if match:
  1142.         return match.group(1, 2)
  1143.     
  1144.     return (user, None)
  1145.  
  1146. _portprog = None
  1147.  
  1148. def splitport(host):
  1149.     """splitport('host:port') --> 'host', 'port'."""
  1150.     global _portprog
  1151.     if _portprog is None:
  1152.         import re
  1153.         _portprog = re.compile('^(.*):([0-9]+)$')
  1154.     
  1155.     match = _portprog.match(host)
  1156.     if match:
  1157.         return match.group(1, 2)
  1158.     
  1159.     return (host, None)
  1160.  
  1161. _nportprog = None
  1162.  
  1163. def splitnport(host, defport = -1):
  1164.     """Split host and port, returning numeric port.
  1165.     Return given default port if no ':' found; defaults to -1.
  1166.     Return numerical port if a valid number are found after ':'.
  1167.     Return None if ':' but not a valid number."""
  1168.     global _nportprog
  1169.     if _nportprog is None:
  1170.         import re
  1171.         _nportprog = re.compile('^(.*):(.*)$')
  1172.     
  1173.     match = _nportprog.match(host)
  1174.     if match:
  1175.         (host, port) = match.group(1, 2)
  1176.         
  1177.         try:
  1178.             if not port:
  1179.                 raise ValueError, 'no digits'
  1180.             
  1181.             nport = int(port)
  1182.         except ValueError:
  1183.             nport = None
  1184.  
  1185.         return (host, nport)
  1186.     
  1187.     return (host, defport)
  1188.  
  1189. _queryprog = None
  1190.  
  1191. def splitquery(url):
  1192.     """splitquery('/path?query') --> '/path', 'query'."""
  1193.     global _queryprog
  1194.     if _queryprog is None:
  1195.         import re
  1196.         _queryprog = re.compile('^(.*)\\?([^?]*)$')
  1197.     
  1198.     match = _queryprog.match(url)
  1199.     if match:
  1200.         return match.group(1, 2)
  1201.     
  1202.     return (url, None)
  1203.  
  1204. _tagprog = None
  1205.  
  1206. def splittag(url):
  1207.     """splittag('/path#tag') --> '/path', 'tag'."""
  1208.     global _tagprog
  1209.     if _tagprog is None:
  1210.         import re
  1211.         _tagprog = re.compile('^(.*)#([^#]*)$')
  1212.     
  1213.     match = _tagprog.match(url)
  1214.     if match:
  1215.         return match.group(1, 2)
  1216.     
  1217.     return (url, None)
  1218.  
  1219.  
  1220. def splitattr(url):
  1221.     """splitattr('/path;attr1=value1;attr2=value2;...') ->
  1222.         '/path', ['attr1=value1', 'attr2=value2', ...]."""
  1223.     words = url.split(';')
  1224.     return (words[0], words[1:])
  1225.  
  1226. _valueprog = None
  1227.  
  1228. def splitvalue(attr):
  1229.     """splitvalue('attr=value') --> 'attr', 'value'."""
  1230.     global _valueprog
  1231.     if _valueprog is None:
  1232.         import re
  1233.         _valueprog = re.compile('^([^=]*)=(.*)$')
  1234.     
  1235.     match = _valueprog.match(attr)
  1236.     if match:
  1237.         return match.group(1, 2)
  1238.     
  1239.     return (attr, None)
  1240.  
  1241.  
  1242. def splitgophertype(selector):
  1243.     """splitgophertype('/Xselector') --> 'X', 'selector'."""
  1244.     if selector[:1] == '/' and selector[1:2]:
  1245.         return (selector[1], selector[2:])
  1246.     
  1247.     return (None, selector)
  1248.  
  1249. _hextochr = dict((lambda [outmost-iterable]: for i in [outmost-iterable]:
  1250. ('%02x' % i, chr(i)))(range(256)))
  1251. _hextochr.update((lambda [outmost-iterable]: for i in [outmost-iterable]:
  1252. ('%02X' % i, chr(i)))(range(256)))
  1253.  
  1254. def unquote(s):
  1255.     """unquote('abc%20def') -> 'abc def'."""
  1256.     res = s.split('%')
  1257.     for i in xrange(1, len(res)):
  1258.         item = res[i]
  1259.         
  1260.         try:
  1261.             res[i] = _hextochr[item[:2]] + item[2:]
  1262.         continue
  1263.         except KeyError:
  1264.             res[i] = '%' + item
  1265.             continue
  1266.             except UnicodeDecodeError:
  1267.                 res[i] = unichr(int(item[:2], 16)) + item[2:]
  1268.                 continue
  1269.             
  1270.         return ''.join(res)
  1271.  
  1272.  
  1273.  
  1274. def unquote_plus(s):
  1275.     """unquote('%7e/abc+def') -> '~/abc def'"""
  1276.     s = s.replace('+', ' ')
  1277.     return unquote(s)
  1278.  
  1279. always_safe = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.-'
  1280. _safemaps = { }
  1281.  
  1282. def quote(s, safe = '/'):
  1283.     '''quote(\'abc def\') -> \'abc%20def\'
  1284.  
  1285.     Each part of a URL, e.g. the path info, the query, etc., has a
  1286.     different set of reserved characters that must be quoted.
  1287.  
  1288.     RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
  1289.     the following reserved characters.
  1290.  
  1291.     reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
  1292.                   "$" | ","
  1293.  
  1294.     Each of these characters is reserved in some component of a URL,
  1295.     but not necessarily in all of them.
  1296.  
  1297.     By default, the quote function is intended for quoting the path
  1298.     section of a URL.  Thus, it will not encode \'/\'.  This character
  1299.     is reserved, but in typical usage the quote function is being
  1300.     called on a path where the existing slash characters are used as
  1301.     reserved characters.
  1302.     '''
  1303.     cachekey = (safe, always_safe)
  1304.     
  1305.     try:
  1306.         safe_map = _safemaps[cachekey]
  1307.     except KeyError:
  1308.         safe += always_safe
  1309.         safe_map = { }
  1310.         for i in range(256):
  1311.             c = chr(i)
  1312.             if not c in safe or c:
  1313.                 pass
  1314.             safe_map[c] = '%%%02X' % i
  1315.         
  1316.         _safemaps[cachekey] = safe_map
  1317.  
  1318.     res = map(safe_map.__getitem__, s)
  1319.     return ''.join(res)
  1320.  
  1321.  
  1322. def quote_plus(s, safe = ''):
  1323.     """Quote the query fragment of a URL; replacing ' ' with '+'"""
  1324.     if ' ' in s:
  1325.         s = quote(s, safe + ' ')
  1326.         return s.replace(' ', '+')
  1327.     
  1328.     return quote(s, safe)
  1329.  
  1330.  
  1331. def urlencode(query, doseq = 0):
  1332.     '''Encode a sequence of two-element tuples or dictionary into a URL query string.
  1333.  
  1334.     If any values in the query arg are sequences and doseq is true, each
  1335.     sequence element is converted to a separate parameter.
  1336.  
  1337.     If the query arg is a sequence of two-element tuples, the order of the
  1338.     parameters in the output will match the order of parameters in the
  1339.     input.
  1340.     '''
  1341.     if hasattr(query, 'items'):
  1342.         query = query.items()
  1343.     else:
  1344.         
  1345.         try:
  1346.             if len(query) and not isinstance(query[0], tuple):
  1347.                 raise TypeError
  1348.         except TypeError:
  1349.             (ty, va, tb) = sys.exc_info()
  1350.             raise TypeError, 'not a valid non-string sequence or mapping object', tb
  1351.  
  1352.     l = []
  1353.     if not doseq:
  1354.         for k, v in query:
  1355.             k = quote_plus(str(k))
  1356.             v = quote_plus(str(v))
  1357.             l.append(k + '=' + v)
  1358.         
  1359.     else:
  1360.         for k, v in query:
  1361.             k = quote_plus(str(k))
  1362.             if isinstance(v, str):
  1363.                 v = quote_plus(v)
  1364.                 l.append(k + '=' + v)
  1365.                 continue
  1366.             if _is_unicode(v):
  1367.                 v = quote_plus(v.encode('ASCII', 'replace'))
  1368.                 l.append(k + '=' + v)
  1369.                 continue
  1370.             
  1371.             try:
  1372.                 x = len(v)
  1373.             except TypeError:
  1374.                 v = quote_plus(str(v))
  1375.                 l.append(k + '=' + v)
  1376.                 continue
  1377.  
  1378.             for elt in v:
  1379.                 l.append(k + '=' + quote_plus(str(elt)))
  1380.             
  1381.         
  1382.     return '&'.join(l)
  1383.  
  1384.  
  1385. def getproxies_environment():
  1386.     '''Return a dictionary of scheme -> proxy server URL mappings.
  1387.  
  1388.     Scan the environment for variables named <scheme>_proxy;
  1389.     this seems to be the standard convention.  If you need a
  1390.     different way, you can pass a proxies dictionary to the
  1391.     [Fancy]URLopener constructor.
  1392.  
  1393.     '''
  1394.     proxies = { }
  1395.     for name, value in os.environ.items():
  1396.         name = name.lower()
  1397.         if value and name[-6:] == '_proxy':
  1398.             proxies[name[:-6]] = value
  1399.             continue
  1400.     
  1401.     return proxies
  1402.  
  1403. if sys.platform == 'darwin':
  1404.     
  1405.     def getproxies_internetconfig():
  1406.         '''Return a dictionary of scheme -> proxy server URL mappings.
  1407.  
  1408.         By convention the mac uses Internet Config to store
  1409.         proxies.  An HTTP proxy, for instance, is stored under
  1410.         the HttpProxy key.
  1411.  
  1412.         '''
  1413.         
  1414.         try:
  1415.             import ic
  1416.         except ImportError:
  1417.             return { }
  1418.  
  1419.         
  1420.         try:
  1421.             config = ic.IC()
  1422.         except ic.error:
  1423.             return { }
  1424.  
  1425.         proxies = { }
  1426.         if 'UseHTTPProxy' in config and config['UseHTTPProxy']:
  1427.             
  1428.             try:
  1429.                 value = config['HTTPProxyHost']
  1430.             except ic.error:
  1431.                 pass
  1432.  
  1433.             proxies['http'] = 'http://%s' % value
  1434.         
  1435.         return proxies
  1436.  
  1437.     
  1438.     def proxy_bypass(x):
  1439.         return 0
  1440.  
  1441.     
  1442.     def getproxies():
  1443.         if not getproxies_environment():
  1444.             pass
  1445.         return getproxies_internetconfig()
  1446.  
  1447. elif os.name == 'nt':
  1448.     
  1449.     def getproxies_registry():
  1450.         '''Return a dictionary of scheme -> proxy server URL mappings.
  1451.  
  1452.         Win32 uses the registry to store proxies.
  1453.  
  1454.         '''
  1455.         proxies = { }
  1456.         
  1457.         try:
  1458.             import _winreg
  1459.         except ImportError:
  1460.             return proxies
  1461.  
  1462.         
  1463.         try:
  1464.             internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings')
  1465.             proxyEnable = _winreg.QueryValueEx(internetSettings, 'ProxyEnable')[0]
  1466.             if proxyEnable:
  1467.                 proxyServer = str(_winreg.QueryValueEx(internetSettings, 'ProxyServer')[0])
  1468.                 if '=' in proxyServer:
  1469.                     for p in proxyServer.split(';'):
  1470.                         (protocol, address) = p.split('=', 1)
  1471.                         import re
  1472.                         if not re.match('^([^/:]+)://', address):
  1473.                             address = '%s://%s' % (protocol, address)
  1474.                         
  1475.                         proxies[protocol] = address
  1476.                     
  1477.                 elif proxyServer[:5] == 'http:':
  1478.                     proxies['http'] = proxyServer
  1479.                 else:
  1480.                     proxies['http'] = 'http://%s' % proxyServer
  1481.                     proxies['ftp'] = 'ftp://%s' % proxyServer
  1482.             
  1483.             internetSettings.Close()
  1484.         except (WindowsError, ValueError, TypeError):
  1485.             pass
  1486.  
  1487.         return proxies
  1488.  
  1489.     
  1490.     def getproxies():
  1491.         '''Return a dictionary of scheme -> proxy server URL mappings.
  1492.  
  1493.         Returns settings gathered from the environment, if specified,
  1494.         or the registry.
  1495.  
  1496.         '''
  1497.         if not getproxies_environment():
  1498.             pass
  1499.         return getproxies_registry()
  1500.  
  1501.     
  1502.     def proxy_bypass(host):
  1503.         
  1504.         try:
  1505.             import _winreg
  1506.             import re
  1507.         except ImportError:
  1508.             return 0
  1509.  
  1510.         
  1511.         try:
  1512.             internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings')
  1513.             proxyEnable = _winreg.QueryValueEx(internetSettings, 'ProxyEnable')[0]
  1514.             proxyOverride = str(_winreg.QueryValueEx(internetSettings, 'ProxyOverride')[0])
  1515.         except WindowsError:
  1516.             return 0
  1517.  
  1518.         if not proxyEnable or not proxyOverride:
  1519.             return 0
  1520.         
  1521.         host = [
  1522.             host]
  1523.         
  1524.         try:
  1525.             addr = socket.gethostbyname(host[0])
  1526.             if addr != host:
  1527.                 host.append(addr)
  1528.         except socket.error:
  1529.             pass
  1530.  
  1531.         proxyOverride = proxyOverride.split(';')
  1532.         i = 0
  1533.         while i < len(proxyOverride):
  1534.             if proxyOverride[i] == '<local>':
  1535.                 proxyOverride[i:i + 1] = [
  1536.                     'localhost',
  1537.                     '127.0.0.1',
  1538.                     socket.gethostname(),
  1539.                     socket.gethostbyname(socket.gethostname())]
  1540.             
  1541.             i += 1
  1542.         for test in proxyOverride:
  1543.             test = test.replace('.', '\\.')
  1544.             test = test.replace('*', '.*')
  1545.             test = test.replace('?', '.')
  1546.             for val in host:
  1547.                 if re.match(test, val, re.I):
  1548.                     return 1
  1549.                     continue
  1550.             
  1551.         
  1552.         return 0
  1553.  
  1554. else:
  1555.     getproxies = getproxies_environment
  1556.     
  1557.     def proxy_bypass(host):
  1558.         return 0
  1559.  
  1560.  
  1561. def test1():
  1562.     s = ''
  1563.     for i in range(256):
  1564.         s = s + chr(i)
  1565.     
  1566.     s = s * 4
  1567.     t0 = time.time()
  1568.     qs = quote(s)
  1569.     uqs = unquote(qs)
  1570.     t1 = time.time()
  1571.     if uqs != s:
  1572.         print 'Wrong!'
  1573.     
  1574.     print repr(s)
  1575.     print repr(qs)
  1576.     print repr(uqs)
  1577.     print round(t1 - t0, 3), 'sec'
  1578.  
  1579.  
  1580. def reporthook(blocknum, blocksize, totalsize):
  1581.     print 'Block number: %d, Block size: %d, Total size: %d' % (blocknum, blocksize, totalsize)
  1582.  
  1583.  
  1584. def test(args = []):
  1585.     if not args:
  1586.         args = [
  1587.             '/etc/passwd',
  1588.             'file:/etc/passwd',
  1589.             'file://localhost/etc/passwd',
  1590.             'ftp://ftp.python.org/pub/python/README',
  1591.             'http://www.python.org/index.html']
  1592.         if hasattr(URLopener, 'open_https'):
  1593.             args.append('https://synergy.as.cmu.edu/~geek/')
  1594.         
  1595.     
  1596.     
  1597.     try:
  1598.         for url in args:
  1599.             print '-' * 10, url, '-' * 10
  1600.             (fn, h) = urlretrieve(url, None, reporthook)
  1601.             print fn
  1602.             if h:
  1603.                 print '======'
  1604.                 for k in h.keys():
  1605.                     print k + ':', h[k]
  1606.                 
  1607.                 print '======'
  1608.             
  1609.             fp = open(fn, 'rb')
  1610.             data = fp.read()
  1611.             del fp
  1612.             if '\r' in data:
  1613.                 table = string.maketrans('', '')
  1614.                 data = data.translate(table, '\r')
  1615.             
  1616.             print data
  1617.             (fn, h) = (None, None)
  1618.         
  1619.         print '-' * 40
  1620.     finally:
  1621.         urlcleanup()
  1622.  
  1623.  
  1624.  
  1625. def main():
  1626.     import getopt
  1627.     import sys
  1628.     
  1629.     try:
  1630.         (opts, args) = getopt.getopt(sys.argv[1:], 'th')
  1631.     except getopt.error:
  1632.         msg = None
  1633.         print msg
  1634.         print 'Use -h for help'
  1635.         return None
  1636.  
  1637.     t = 0
  1638.     for o, a in opts:
  1639.         if o == '-t':
  1640.             t = t + 1
  1641.         
  1642.         if o == '-h':
  1643.             print 'Usage: python urllib.py [-t] [url ...]'
  1644.             print '-t runs self-test;', 'otherwise, contents of urls are printed'
  1645.             return None
  1646.             continue
  1647.     
  1648.     if t:
  1649.         if t > 1:
  1650.             test1()
  1651.         
  1652.         test(args)
  1653.     elif not args:
  1654.         print 'Use -h for help'
  1655.     
  1656.     for url in args:
  1657.         print urlopen(url).read(),
  1658.     
  1659.  
  1660. if __name__ == '__main__':
  1661.     main()
  1662.  
  1663.